<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>网页聊天登录</title>
  <link rel="stylesheet" href="css/login.css">
</head>
<body>
  <!-- 背景图片容器 -->
  <div class="background-container">
    <div class="background-overlay"></div>
  </div>

  <!-- 登录容器 -->
  <div class="login-container">
    <h2>网页聊天室</h2>
    <div class="row">
      <label>用户名</label>
      <input type="text" , id="username">
    </div>
    <div class="row">
      <label>密码</label>
      <input type="password" , id="password">
    </div>
    <div>
      <button id="submit">登录</button>
    </div>
    <div class="row">
      <button id="register-button">注册</button>
    </div>
  </div>

  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    let submitButton = document.querySelector('#submit');
    submitButton.onclick = function() {
      // 先获取到输入框中的内容
      let username = document.querySelector('#username').value;
      let password = document.querySelector('#password').value;
      if (username == '' || password == '') {
        alert("当前输入的用户名或者密码为空!");
        return;
      }

      //  再发送 ajax 请求进行登录
      $.ajax({
        url: '/login',
        type: 'post',
        data: {
          username: username,
          password: password
        },
        success: function(body) {
          //  处理响应
          // 此处的 body 相当于响应的 user 对象.
          if (body && body.userId > 0) {
            // 登录成功!
            alert("登录成功!");
            // 跳转到客户端主页面 (聊天页面)
            // 注意!! 当前尚未创建这个页面, 一会运行会出现 404
            location.assign('/client.html');
          } else {
            alert("登录失败!请重新登录！");
            location.assign('/login.html');
          }
        }
      });
    }
    let submitButton2 = document.querySelector('#register-button');
    submitButton2.onclick = function() {
      window.location.href = 'register.html';
    }
  </script>
</body>
</html>